package com.yf.mediaserver.gb.sip.processors.req.impl;

import com.yf.mediaserver.gb.sip.processors.SIPProcessorObserver;
import com.yf.mediaserver.gb.sip.processors.req.ISIPRequestProcessor;
import com.yf.mediaserver.gb.sip.processors.req.SIPRequestProcessorParent;
import com.yf.mediaserver.gb.sip.util.SipUtils;
import gov.nist.javax.sip.message.SIPRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sip.InvalidArgumentException;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.header.CallIdHeader;
import javax.sip.message.Response;
import java.text.ParseException;


/**
 *  * @description: 接受INVITE请求   通常来自别的平台
 */
@Slf4j
@Component
public class InviteRequestProcessor extends SIPRequestProcessorParent implements InitializingBean ,ISIPRequestProcessor {

    public final static String method = "INVITE";

    @Resource
    private SIPProcessorObserver processorObserver;

    @Override
    public void afterPropertiesSet() throws Exception {
        processorObserver.addRequestProcessor(method,this);
    }

    @Override
    public void process(RequestEvent event) {

        try {
            SIPRequest request = (SIPRequest)event.getRequest();
            String channelId = SipUtils.getChannelIdFromRequest(request);
            String requesterId = SipUtils.getUserIdFromFromHeader(request);
            CallIdHeader callIdHeader = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
            if (requesterId == null || channelId == null) {
                log.info("无法从FromHeader的Address中获取到平台id，返回400");
                // 参数不全， 发400，请求错误
                try {
                    responseAck(request, Response.BAD_REQUEST);
                } catch (SipException | InvalidArgumentException | ParseException e) {
                    log.error("[命令发送失败] invite BAD_REQUEST: {}", e.getMessage());
                }
                return;
            }

            responseAck(request, Response.TRYING);
        } catch (Exception e) {
          log.error("异常：",e);
        }
    }



}
